import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/user_model.dart';
import '../../core/models/travel_log_model.dart';
import '../../core/models/topic_model.dart';
import '../../core/providers/user_provider.dart';
import '../../core/providers/travel_log_provider.dart';
import '../../core/providers/topic_provider.dart';
import '../../core/providers/private_chat_provider.dart';
import '../../core/providers/follow_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class OtherUserProfileScreen extends ConsumerStatefulWidget {
  final String userId;

  const OtherUserProfileScreen({super.key, required this.userId});

  @override
  ConsumerState<OtherUserProfileScreen> createState() =>
      _OtherUserProfileScreenState();
}

class _OtherUserProfileScreenState extends ConsumerState<OtherUserProfileScreen>
    with SingleTickerProviderStateMixin {
  int _currentTabIndex = 0;
  late TabController _tabBarController;

  @override
  void initState() {
    super.initState();
    _tabBarController = TabController(length: 2, vsync: this);
    _tabBarController.addListener(() {
      setState(() {
        _currentTabIndex = _tabBarController.index;
      });
    });
  }

  @override
  void dispose() {
    _tabBarController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(child: _buildPageContent()),
      ),
    );
  }

  Widget _buildPageContent() {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    final targetUser = allUsers.firstWhere(
      (user) => user.id == widget.userId,
      orElse: () => UserDataEntity.empty(),
    );

    if (!targetUser.isValid) {
      return _buildUserNotFoundView();
    }

    return _buildMainContent(targetUser);
  }

  Widget _buildUserNotFoundView() {
    return [
      _buildHeaderBar(),
      SizedBox(height: 100.h),

      Text(
        'User not found',
        style: TextStyle(
          fontSize: 18.sp,
          color: Colors.white,
          fontWeight: FontWeight.w600,
          fontFamily: 'PoetsenOne',
        ),
      ).center(),
    ].toColumn();
  }

  Widget _buildMainContent(UserDataEntity targetUser) {
    return [
      _buildHeaderBar(),

      Expanded(
        child: NestedScrollView(
          headerSliverBuilder: (context, innerBoxIsScrolled) {
            return [
              SliverToBoxAdapter(
                child:
                    [
                      SizedBox(height: 20.h),
                      _buildUserInfoSection(targetUser),
                      SizedBox(height: 24.h),
                      _buildTabBar(),
                      SizedBox(height: 16.h),
                    ].toColumn(),
              ),
            ];
          },
          body: _buildTabBarContent(targetUser),
        ),
      ),
    ].toColumn();
  }

  Widget _buildHeaderBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child:
          [
            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black,
              ),
              child: Center(
                child: Icon(Icons.arrow_back_ios)
                    .iconSize(18.sp)
                    .iconColor(Colors.white)
                    .inkWell(onTap: () => Navigator.of(context).pop()),
              ),
            ),

            Spacer(),

            Text(
              'Profile',
              style: TextStyle(
                fontSize: 24.sp,
                color: Colors.black,
                fontWeight: FontWeight.bold,
                fontFamily: 'PoetsenOne',
              ),
            ),

            Spacer(),

            Container(
              width: 30.w,
              height: 30.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.black,
              ),
              child: Icon(AliIcons.iconReport)
                  .iconSize(24.sp)
                  .iconColor(Colors.white)
                  .inkWell(onTap: _handleReportUser),
            ),
          ].toRow(),
    );
  }

  Widget _buildUserInfoSection(UserDataEntity targetUser) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFFDDB31),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child:
          [
            _buildUserInfoRow(targetUser),
            SizedBox(height: 16.h),

            _buildUserDescription(targetUser),
            SizedBox(height: 16.h),

            _buildVisitorSection(),
          ].toColumn(),
    );
  }

  Widget _buildUserInfoRow(UserDataEntity targetUser) {
    return [
      _buildUserAvatarWithFollow(targetUser),
      SizedBox(width: 16.w),

      Expanded(
        child: [
          Text(
            targetUser.username,
            style: TextStyle(
              fontSize: 24.sp,
              color: Colors.black,
              fontWeight: FontWeight.bold,
              fontFamily: 'PoetsenOne',
            ),
          ),
          SizedBox(height: 4.h),
          Text(
            'Last login: ${_formatLastLoginTime(targetUser.lastLoginTime)}',
            style: TextStyle(fontSize: 12.sp, color: Colors.black54),
          ),
        ].toColumn(crossAxisAlignment: CrossAxisAlignment.start),
      ),

      _buildChatButton(targetUser),
    ].toRow();
  }

  Widget _buildUserAvatarWithFollow(UserDataEntity targetUser) {
    final currentUser = ref.watch(userProvider);

    if (currentUser?.id == targetUser.id) {
      return Container(
        width: 81.w,
        height: 81.w,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          border: Border.all(color: Colors.black, width: 2.w),
          image: DecorationImage(
            image: AssetImage(targetUser.avatar),
            fit: BoxFit.cover,
          ),
        ),
      );
    }

    final isFollowing =
        currentUser != null
            ? ref.watch(
              isFollowingProvider({
                'followerId': currentUser.id,
                'followeeId': targetUser.id,
              }),
            )
            : false;

    return Stack(
      children: [
        Container(
          width: 81.w,
          height: 81.w,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            border: Border.all(color: Colors.black, width: 2.w),
            image: DecorationImage(
              image: AssetImage(targetUser.avatar),
              fit: BoxFit.cover,
            ),
          ),
        ),

        Positioned(
          bottom: 0,
          right: 0,
          child: Container(
            width: 24.w,
            height: 24.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Color(0xFF2AB061),
            ),
            child:
                Image.asset(
                  isFollowing
                      ? 'assets/resources/following.png'
                      : 'assets/resources/add_follow.png',
                  width: 20.w,
                  height: 20.w,
                  fit: BoxFit.contain,
                ).center(),
          ).inkWell(onTap: () => _handleFollowUser(targetUser)),
        ),
      ],
    );
  }

  Widget _buildChatButton(UserDataEntity targetUser) {
    return Container(
      width: 32.w,
      height: 32.w,
      decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.black),
      child:
          Icon(
            AliIcons.iconConnect,
          ).iconSize(24.sp).iconColor(Colors.white).center(),
    ).inkWell(onTap: () => _handleChatWithUser(targetUser));
  }

  Widget _buildUserDescription(UserDataEntity targetUser) {
    return Text(
      targetUser.description,
      style: TextStyle(fontSize: 14.sp, color: Colors.black87, height: 1.4),
      textAlign: TextAlign.left,
    );
  }

  Widget _buildVisitorSection() {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();

    final visitors = allUsers.take(5).toList();

    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFFDF5E1),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          [
            SizedBox(
              width: 150.w,
              height: 42.h,
              child: Stack(
                children: [
                  for (int i = 0; i < visitors.length; i++)
                    Positioned(
                      left: (i * 25).toDouble().w,
                      child: _buildVisitorAvatar(visitors[i].avatar),
                    ),
                ],
              ),
            ),
            SizedBox(width: 6.w),

            Text(
              'Visited home page',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.black87,
                fontWeight: FontWeight.w500,
              ),
            ),
          ].toRow(),

          Positioned(
            top: 6.h,
            right: -16.w,
            child: Image.asset(
              'assets/resources/eyes.png',
              width: 40.w,
              height: 33.h,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVisitorAvatar(String imagePath) {
    return Container(
      width: 42.w,
      height: 42.h,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.black, width: 1.w),
        image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.cover),
      ),
    );
  }

  Widget _buildTabBar() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w),
      child: [
        _buildTabBarItem(0, 'assets/resources/home_topic.png'),
        _buildTabBarItem(1, 'assets/resources/home_share.png'),
      ].toRow(mainAxisAlignment: MainAxisAlignment.spaceAround),
    );
  }

  Widget _buildTabBarItem(int index, String imagePath) {
    final isSelected = _currentTabIndex == index;

    return [
      Image.asset(
        imagePath,
        width: 60.w,
        height: 30.h,
        color: isSelected ? null : Colors.white.withValues(alpha: 0.6),
        colorBlendMode: isSelected ? null : BlendMode.modulate,
      ),
      if (isSelected) ...[
        SizedBox(height: 8.h),
        Image.asset(
          'assets/resources/home_select.png',
          width: 40.w,
          height: 8.h,
        ),
      ],
    ].toColumn().inkWell(
      onTap: () {
        _tabBarController.animateTo(index);
      },
    );
  }

  Widget _buildTabBarContent(UserDataEntity targetUser) {
    return TabBarView(
      controller: _tabBarController,
      children: [
        _buildTopicSection(targetUser),
        _buildShareSection(targetUser),
      ],
    );
  }

  Widget _buildTopicSection(UserDataEntity targetUser) {
    final topics = ref.watch(outingTopicProvider);
    final userTopics =
        topics.where((topic) => topic.userId == targetUser.id).toList();

    if (userTopics.isEmpty) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child:
            Image.asset(
              'assets/resources/no.png',
              width: 176.w,
              height: 176.w,
            ).center(),
      );
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: ListView.builder(
        padding: EdgeInsets.zero,
        itemCount: userTopics.length,
        itemBuilder: (context, index) {
          final topic = userTopics[index];
          return _buildTopicCard(topic, index);
        },
      ),
    );
  }

  Widget _buildTopicCard(OutingTopicEntity topic, int index) {
    final isOdd = (index + 1) % 2 == 1;
    final backgroundImage =
        isOdd
            ? 'assets/resources/topic_card_bg_1.png'
            : 'assets/resources/topic_card_bg_2.png';

    return Container(
      height: 94.h,
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage(backgroundImage),
          fit: BoxFit.fill,
        ),
      ),
      child:
          [
            Container(
              width: 54.w,
              height: 54.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Color(0xFF2AB061),
              ),
              child:
                  Image.asset(
                    'assets/resources/topic_icon.png',
                    width: 28.w,
                    height: 28.w,
                  ).center(),
            ),
            SizedBox(width: 16.w),
            Expanded(
              child: [
                Text(
                  topic.description,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.black,
                    height: 1.43,
                  ),
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                ),
              ].toColumn(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
              ),
            ),
          ].toRow(),
    ).inkWell(
      onTap: () {
        GoRouter.of(context).push('/topic-detail/${topic.topicId}');
      },
    );
  }

  Widget _buildShareSection(UserDataEntity targetUser) {
    final travelLogs = ref.watch(travelLogProvider);
    final userLogs =
        travelLogs.where((log) => log.userId == targetUser.id).toList();

    if (userLogs.isEmpty) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w),
        child:
            Image.asset(
              'assets/resources/no.png',
              width: 176.w,
              height: 176.w,
            ).center(),
      );
    }

    final itemHeight = 262.h;
    final itemSpacing = 12.h;
    final columnCount = (userLogs.length / 2).ceil();
    final totalHeight = columnCount * (itemHeight + itemSpacing);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      height: totalHeight,
      child: [
        Expanded(
          child:
              [
                for (int i = 0; i < userLogs.length; i += 2)
                  if (i < userLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(userLogs[i]),
                    ),
              ].toColumn(),
        ),
        SizedBox(width: 12.w),
        Expanded(
          child:
              [
                for (int i = 1; i < userLogs.length; i += 2)
                  if (i < userLogs.length)
                    Padding(
                      padding: EdgeInsets.only(bottom: 12.h),
                      child: _buildTravelLogCard(userLogs[i]),
                    ),
              ].toColumn(),
        ),
      ].toRow(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  Widget _buildTravelLogCard(TravelLogEntity travelLog) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final currentUser = ref.watch(userProvider);

    final user = allUsers.firstWhere(
      (u) => u.id == travelLog.userId,
      orElse: () => allUsers.first,
    );

    final isLiked =
        currentUser != null && travelLog.isLikedByUser(currentUser.id);

    return AspectRatio(
      aspectRatio: 182 / 262,
      child: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/log_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child:
            [
              Expanded(
                child: Container(
                  margin: EdgeInsets.all(8.w),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    image: DecorationImage(
                      image: AssetImage(
                        travelLog.isVideoType && travelLog.videoCoverUrl != null
                            ? travelLog.videoCoverUrl!
                            : travelLog.mediaUrl,
                      ),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child:
                      travelLog.isVideoType
                          ? Icon(AliIcons.iconPlayFill)
                              .iconSize(22.sp)
                              .iconColor(Colors.white.withValues(alpha: 0.8))
                              .center()
                          : null,
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                alignment: Alignment.centerLeft,
                child: Text(
                  travelLog.content,
                  style: TextStyle(
                    fontSize: 10.sp,
                    color: Colors.black87,
                    height: 1.2,
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  textAlign: TextAlign.start,
                ),
              ),
              Container(
                padding: EdgeInsets.all(8.w),
                child:
                    [
                      Container(
                        width: 28.w,
                        height: 28.w,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          image: DecorationImage(
                            image: AssetImage(user.avatar),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Expanded(
                        child: Text(
                          user.username,
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.black87,
                            fontWeight: FontWeight.w500,
                          ),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      [
                        Text(
                          '${travelLog.likeCount}',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: isLiked ? Colors.red : Colors.black,
                            fontWeight:
                                isLiked ? FontWeight.bold : FontWeight.normal,
                          ),
                        ),
                        SizedBox(width: 4.w),
                        Icon(AliIcons.iconGood)
                            .iconSize(18.sp)
                            .iconColor(isLiked ? Colors.red : Colors.grey),
                      ].toRow().inkWell(
                        onTap: () => _handleTravelLogLike(travelLog),
                      ),
                    ].toRow(),
              ),
            ].toColumn(),
      ),
    ).inkWell(
      onTap: () {
        GoRouter.of(context).push('/journey-detail/${travelLog.logId}');
      },
    );
  }

  String _formatLastLoginTime(DateTime lastLoginTime) {
    final now = DateTime.now();
    final difference = now.difference(lastLoginTime);

    if (difference.inDays > 0) {
      return '${difference.inDays} days ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hours ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minutes ago';
    } else {
      return 'Just now';
    }
  }

  void _handleReportUser() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) {
        ToastHelper.success('Report submitted successfully', context: context);
        if (mounted) {
          GoRouter.of(context).pop();
        }
      },
      onCancelPressed: () {},
    );
  }

  void _handleFollowUser(UserDataEntity targetUser) async {
    final currentUser = ref.read(userProvider);

    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
      );
      return;
    }

    if (currentUser.id == targetUser.id) {
      return;
    }

    final followNotifier = ref.read(userFollowProvider.notifier);

    final isCurrentlyFollowing = followNotifier.isFollowing(
      currentUser.id,
      targetUser.id,
    );

    bool success;
    if (isCurrentlyFollowing) {
      success = await followNotifier.unfollowUser(
        followerId: currentUser.id,
        followeeId: targetUser.id,
      );

      if (mounted) {
        if (success) {
          ToastHelper.success(
            'Unfollowed ${targetUser.username}',
            context: context,
          );
        } else {
          ToastHelper.error('Failed to unfollow user', context: context);
        }
      }
    } else {
      success = await followNotifier.followUser(
        followerId: currentUser.id,
        followeeId: targetUser.id,
      );

      if (mounted) {
        if (success) {
          ToastHelper.success(
            'Following ${targetUser.username}',
            context: context,
          );
        } else {
          ToastHelper.error('Failed to follow user', context: context);
        }
      }
    }
  }

  void _handleChatWithUser(UserDataEntity targetUser) async {
    final currentUser = ref.read(userProvider);

    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
      );
      return;
    }

    final privateChatNotifier = ref.read(privateChatProvider.notifier);

    final existingConversation = privateChatNotifier
        .getConversationBetweenUsers(currentUser.id, targetUser.id);

    if (existingConversation != null) {
      GoRouter.of(context).push(
        '/private-chat',
        extra: {
          'conversationId': existingConversation.conversationId,
          'otherUserId': targetUser.id,
        },
      );
    } else {
      final conversationId = await privateChatNotifier.createConversation(
        userId1: currentUser.id,
        userId2: targetUser.id,
        userName1: currentUser.username,
        userName2: targetUser.username,
        userAvatar1: currentUser.avatar,
        userAvatar2: targetUser.avatar,
      );

      if (conversationId != null && mounted) {
        GoRouter.of(context).push(
          '/private-chat',
          extra: {
            'conversationId': conversationId,
            'otherUserId': targetUser.id,
          },
        );
      }
    }
  }

  void _handleTravelLogLike(TravelLogEntity travelLog) async {
    final currentUser = ref.read(userProvider);

    if (currentUser == null) {
      PopupHelper.showLoginDialog(
        context,
        onLoginPressed: () {
          GoRouter.of(context).push('/login');
        },
      );
      return;
    }

    final travelLogNotifier = ref.read(travelLogProvider.notifier);

    try {
      final wasLiked = travelLog.isLikedByUser(currentUser.id);

      final success = await travelLogNotifier.toggleLike(
        travelLog.logId,
        currentUser.id,
      );

      if (mounted && success) {
        if (wasLiked) {
          ToastHelper.info('Like removed', context: context);
        } else {
          ToastHelper.success('Liked!', context: context);
        }
      } else if (mounted && !success) {
        ToastHelper.error('Failed to update like status', context: context);
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('An error occurred', context: context);
      }
    }
  }
}
